package com.ultrapower.mapper;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.client.Result;

import com.ultrapower.bean.AcceptApplicationBean;
import com.ultrapower.bean.ApplicationBean;
import com.ultrapower.buffer.Buffer;
import com.ultrapower.buffer.OffsetFixedBuffer;

/**
 * 
 * @author 
 * 
 */
public class HostApplicationMapperVer2 implements RowMapper<List<AcceptApplicationBean>> {


    public List<AcceptApplicationBean> mapRow(Result result, int rowNum) throws Exception {
        if (result.isEmpty()) {
            return Collections.emptyList();
        }
//       readRowKey(result.getRow());

        final List<AcceptApplicationBean> acceptApplicationList = new ArrayList<>(result.size());
        for (Cell cell : result.rawCells()) {
        	AcceptApplicationBean acceptedApplication = createAcceptedApplication(cell);
            acceptApplicationList.add(acceptedApplication);
        }
        return acceptApplicationList;
    }

//    private void readRowKey(byte[] rowKey) {
//        final Buffer rowKeyBuffer= new FixedBuffer(rowKey);
//        final String parentApplicationName = rowKeyBuffer.readPadStringAndRightTrim(HBaseTables.APPLICATION_NAME_MAX_LEN);
//        final short parentApplicationServiceType = rowKeyBuffer.readShort();
//        final long timeSlot = TimeUtils.recoveryTimeMillis(rowKeyBuffer.readLong());
//
//        if (logger.isDebugEnabled()) {
//            logger.debug("parentApplicationName:{}/{} time:{}", parentApplicationName, parentApplicationServiceType, timeSlot);
//        }
//    }

    private AcceptApplicationBean createAcceptedApplication(Cell cell) {
        Buffer reader = new OffsetFixedBuffer(cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength());
        String host = reader.readPrefixedString();
        String bindApplicationName = reader.readPrefixedString();
        short bindServiceTypeCode = reader.readShort();

        final ApplicationBean bindApplication = new ApplicationBean(bindApplicationName, bindServiceTypeCode);
        return new AcceptApplicationBean(host, bindApplication);
    }
}
